import jwt
from flask import current_app
from datetime import datetime, timedelta


def generate_token(payload, expire, secret=None):
    """
    生成token
    """
    _payload = {
        'exp': expire
    }
    _payload.update(payload)
    if not secret:
        secret = current_app.config['JWT_SECRET']
    token = jwt.encode(_payload, secret, algorithm='HS256')
    return token


def verify_token(token, secret=None):
    """
    解析token
    """
    if not secret:
        secret = current_app.config['JWT_SECRET']
    payload = jwt.decode(token, secret, algorithms='HS256')
    if not payload:
        payload = None
    return payload


def create_token(user_id, refresh=True):
    """
    生成token,refresh_token
    """
    expire = datetime.utcnow() + timedelta(hours=2)
    token = generate_token({'user_id': user_id}, expire)
    if refresh:
        expire = datetime.utcnow() + timedelta(days=15)
        refresh_token = generate_token({'user_id': user_id, 'is_refresh': True}, expire)
    else:
        refresh_token = None
    return token, refresh_token
